soda()
	._page('iam_permission')
	._module(['sdTreeTable'])
	._api('/v1/iam/permission')
	._query(['name^like^', 'state^eq^-1'])
	._orderBy(['sortId^desc'])
	._run((unit) => {
		let tb = null;
		// Api
		unit.api['list'] = '/v1/iam/permission/get/all';
		
		// 表单配置
		unit.templateForm['verify'] = ['name'];
		unit.templateForm['items'] = [
			{code: 1, name:'name', title:'名称', placeholder:'请输入名称', attr: 'maxlength=20'},
			{code: 1, name:'icon', title:'图标', placeholder:'对应layui的图标库', attr: 'maxlength=20'},
			{code: 1, name:'sortId', title:'排序', type: 'number'},
			{code: 2, name:'state', title:'状态', options: unit.globalConstant['enableState']},
			{code: 5, type:'text', name:'remark', title:'备注', placeholder:'备注信息'}
		];
		let formMenu = {}, formAuth = {};
			
		formMenu['verify'] = ['name', 'uri'];
		formMenu['items'] = [
			{code: 1, name:'name', title:'名称', placeholder:'请输入名称', attr: 'maxlength=20'},
			{code: 1, name:'uri', title:'路由', placeholder:'请输入名称html路由', attr: 'maxlength=100'},
			{code: 1, name:'sortId', title:'排序', type: 'number'},
			{code: 2, name:'state', title:'状态', options: unit.globalConstant['enableState']},
			{code: 5, type:'text', name:'remark', title:'备注', placeholder:'备注信息'}
		]
		
		formAuth['verify'] = ['name', 'event', 'flag'];
		formAuth['items'] = [
			{code: 1, name:'name', title:'名称', placeholder:'请输入名称', attr: 'maxlength=20'},
			{code: 1, name:'event', title:'JS事件', placeholder:'请输入JS事件', attr: 'maxlength=30'},
			{code: 2, name:'position', title:'位置', options: unit.globalConstant['position']},
			{code: 1, name:'flag', title:'Api标识', placeholder:'请输入Api标识', attr: 'maxlength=50'},
			{code: 1, name:'sortId', title:'排序', type: 'number'},
			{code: 2, name:'state', title:'状态', options: unit.globalConstant['enableState']},
			{code: 5, type:'text', name:'remark', title:'备注', placeholder:'备注信息'}
		];
			
		// 表格基础配置
		unit.templateTable['id'] = 'tree-table';
		unit.templateTable['cols'] = [
			{field: 'title', title: '名称', align: 'left', width: '200px', template(obj){
			    return formatter.title(obj);
			}},
			{field: 'uri', title: '路由/事件', template(obj){
			    if(obj.level == 3){
			        return obj.event || '';
			    }else{
			        return obj.uri || '';
			    }
			}},
			{field: 'icon', title: '图标', align: 'center', minWidth: '50px', template(obj){
			    if(obj.level == 3){
			        return unit.sdFormat['json']['get'](unit.globalConstant['position'], obj.position, 'value').flag;
			    }else{
			        return '<i class="layui-icon '+obj.icon+'"></i>' || '';
			    }
			}},
			{field: 'flag', title: '权限标识', template(obj){
			    return obj.flag || '';
			}},
			{field: 'sortId', title: '排序', align: 'center'},
			{title: '操作',align: 'center',width: '160px', template(obj){
			    return formatter.btn(obj)
			}}
		];
		unit.templateTable['btns'] = [
			{opt: 'add', event(row){
				unit.templateDialog['form'](row)
			}},
			{opt: 'edit', event(row){
				unit.templateDialog['form'](row, row.id)
			}},
			{opt: 'delete', event(row){
				unit.templateDialog['delete'](row)
			}},
			{opt: 'curd', event(row){
				unit.templateDialog['curd'](row)
			}},
		]
		//弹出层
		unit.templateDialog['form'] = (data, optId) => {
			if(optId){
			    data.level = data.level - 1;
			}
			let configForm = null, formTitle = '', formData = null;
			if(data.level == 0){
			    configForm = unit.templateForm;
			    formTitle = '功能菜单管理';
			}
			if(data.level == 1){
			    configForm = formMenu;
			    formTitle = '权限菜单管理';
			}
			if(data.level == 2){
			    configForm = formAuth;
			    formTitle = '权限管理';
			}
			if(optId){
			    formData = data;
			}
			configForm['id'] = unit.el['form'];
			unit.sdDialog.form({
				title: formTitle,
				height: '500px',
				init() {
					let initData = {};
					unit.sdForm['init']['form'](configForm, formData);
				},
				opt(index) {
					// 获取form
					let form = unit.sdForm['get'](unit.el['form'], configForm['verify']);
					
					// 校验数据
					if (!form.check) {
						unit.sdDialog['tips']['warning'](form.message);
						return false;
					}
					
					// 数据处理
					let val = form.data;
					val['state'] = val['state'] || 1;
					
					if(data.level == 0){
					    val['moduleId'] = data.mid;
					    val['parentId'] = data.mid;
					}
					if(data.level == 1){
					    val['moduleId'] = data.mid;
					    val['parentId'] = data.id;
					    val['groups'] = "menu";
					}
					if(data.level == 2){
					    val['moduleId'] = data.mid;
					    val['parentId'] = data.id;
					    val['position'] = val['position'] || 1;
					    val['groups'] = "auth";
					}
					var tem = val;
					if(optId){
					    delete val['moduleId'];
					    delete val['parentId'];
					    val['level'] = data.level + 1;
					}
			
					let param = {
						url: unit.api['crud'],
						data: val,
						tips: true,
						callback(d) {
							val['id'] = d.id;
							val['title'] = val['name'];
							val['pid'] = val['parentId'] || data['pid'];
							val['mid'] = val['moduleId'] || data['mid'];
							if(formData){
							    // 修改对象
							    tb.data = unit.sdFormat['json']['remove'](tb.data, data.id);
							    tb.data.push(val);
							}else{
							    tb.data.push(val);
							}
							unit.sdTreeTable['refresh'](tb);
							unit.sdForm['init']['form'](configForm);
							if(formData){
								unit.sdDialog['close'](index);
							}
						}
					}
					// 操作
					formData ? unit.sdHttp['put'](param, formData.id) : unit.sdHttp['post'](param);
				}
			})
		}
		unit.templateDialog['delete'] = (data) => {
			unit.sdDialog.confirm({
				title: "是否要删除这条数据?",
				submit() {
					let param = {
						url: unit.api['crud'],
						callback() {
							tb.data = unit.sdFormat['json']['remove'](tb.data, data.id);
							unit.sdTreeTable['refresh'](tb);
						}
					}
					unit.sdHttp['delete'](param, data.id);
				}
			});
		}
		unit.templateDialog['curd'] = (data) => {
			unit.sdDialog.confirm({
				title: "是否马上生成CRUD权限清单?",
				submit() {
					var Q = new Queue();
					let val = {}, key = ((data.uri).substring(1, (data.uri).length)).replace('/', ':');
					key = key.replace('/index', '')
					val['moduleId'] = data.mid;
					val['parentId'] = data.id;
					val['groups'] = 'auth';
					val['state'] = 1;
					let len = 0;
					let param = {
						url: unit.api['crud'],
						data: val,
						callback(d) {
							len += 1;
							Q.stop();
							if(len == 4){
								request.init()
							}
						}
					}
					
					Q.run(function(){
						val['name'] = '表格';
						val['event'] = 'table';
						val['position'] = 3;
						val['flag'] = key + ':data:list';;
						val['sortId'] = 9;
						delete val['id'];
						param.data = val;
						unit.sdHttp['post'](param)
					});
					
					Q.run(function(){
						val['name'] = '创建';
						val['event'] = 'create';
						val['position'] = 2;
						val['flag'] = key + ':opt:create';;
						val['sortId'] = 9;
						delete val['id'];
						param.data = val;
						unit.sdHttp['post'](param)
					});
					
					Q.run(function(){
						val['name'] = '编辑';
						val['event'] = 'update';
						val['position'] = 1;
						val['flag'] = key + ':opt:update';;
						val['sortId'] = 9;
						delete val['id'];
						param.data = val;
						unit.sdHttp['post'](param)
					});
					
					Q.run(function(){
						val['name'] = '删除';
						val['event'] = 'delete';
						val['position'] = 1;
						val['flag'] = key + ':opt:delete';;
						val['sortId'] = 8;
						delete val['id'];
						param.data = val;
						unit.sdHttp['post'](param)
					});
					
				
					// let param = {
					// 	url: unit.api['crud'],
					// 	callback() {
					// 		tb.data = unit.sdFormat['json']['remove'](tb.data, data.id);
					// 		unit.sdTreeTable['refresh'](tb);
					// 	}
					// }
					// unit.sdHttp['delete'](param, data.id);
				}
			});
		}
		// 数据格式化
		let formatter = {
		    title(item){
		        let style = '';
		        switch(item.level){
		            case 0:
		                style = 'style="font-weight: bold;"';
		                break;
		            case 1:
		                style = 'style="color:#2F4056;"';
		                break;
		            case 2:
		                style = 'style="color:green;"';
		                break;
		            case 3:
		                style = 'style="color:#FF5722;padding-left:8px;"';
		                break;
		        }
		        return '<span class="tree-btn" ' + style + '>&nbsp;' + item.title + '</span>';
		    },
		    btn(item){
		        if(item.level != 3){
		            if(item.level == 0){
		                return ' <a class="tree-btn" lay-filter="add">添加子级</a>';
		            }else{
		                let title = "添加功能";
						let a = "";
		                if(item.level == 2){
		                    title = "添加权限";
							a = '<a class="tree-btn" lay-filter="curd">生成</a> | ';
		                }
		                return a + ' <a class="tree-btn" lay-filter="add">' + title + '</a> | ' +
		                    '<a class="tree-btn" lay-filter="edit">修改</a> | '+
		                    '<a class="tree-btn" lay-filter="delete">删除</a>';
		            }
		        }else{
		            return '<a class="tree-btn" lay-filter="edit">修改</a> | <a class="tree-btn" lay-filter="delete">删除</a>';
		        }
		    }
		}
		
		let request = {
		    init(){
		        let param = {
		            url: unit.api['list'],
		            callback: function (d) {
		                tb.data = d;
		                unit.sdTreeTable['refresh'](tb);
		            }
		        }
		        unit.sdHttp['get'](param);
		    }
		}
		request.init()
		tb = unit.sdTreeTable['init'](unit.templateTable)
	})